/*
 * @Author: XXX
 * @Date: 2022-11-17 17:19:41
 * @LastEditors: XXX
 * @Description: VR全景
 */
import { OrbitControls } from "../vr-lib/jsm/controls/OrbitControls"
const THREE = require('../vr-lib/three/three.weapp.js')

Page({
  data: {
    canvasId: 'canvasGL'
  },
  onLoad: function (options: {vrUrl: string}) {
    wx.showLoading({title: '加载中...'})
    // const url = "https://img1.baidu.com/it/u=1661367446,3113628201&fm=253&fmt=auto&app=138&f=JPEG?w=1000&h=500"
    const arrUrl = ["http://www.yanhuangxueyuan.com/threejs/examples/textures/2294472375_24a3b8ef46_o.jpg"]
    // const arrUrl = [
    //   "../images/VR/w04.png",
    //   "../images/VR/w05.png",
    //   "../images/VR/w06.png",
    //   "../images/VR/w02.png",
    //   "../images/VR/w01.png",
    //   "../images/VR/w03.png",
    // ]
    /* 正方体图片顺序规则：右、左、上、下、前、后 */

    wx.createSelectorQuery()
      .select("#canvasGL")
      .node()
      .exec((res) => {
        // 创建canvas对象
        const canvas = THREE.global.registerCanvas(res[0].node)
        // 记录canvas的id，好在page销毁的时候释放canvas
        this.setData({ canvasId: canvas._canvasId })

        const camera = new THREE.PerspectiveCamera(
          // arrUrl.length === 1 ? 45 : 45,  /* 摄像机视觉，球形和正方体视觉不一样 */
          75,  /* 摄像机视觉，球形和正方体视觉不一样 */
          canvas.width / canvas.height,
          0.01,
          1100
        )
        camera.position.z = canvas.height
        const scene = new THREE.Scene()
        scene.background = new THREE.Color(0xaaaaaa)
        const renderer = new THREE.WebGLRenderer({ antialias: true })

        // renderer.setPixelRatio(systemInfo.pixelRatio) // 不可设置，渲染会崩溃。设置设备像素比。通常用于避免HiDPI设备上绘图模糊
        renderer.setSize(canvas.width, canvas.height) // 设置宽高

        const controls = new OrbitControls(camera, renderer.domElement)
        controls.enableZoom = false /* 是否启动缩放 */
        controls.enablePan = false
        controls.enableDamping = true /* 是否启动阻尼 */
        controls.rotateSpeed = -0.3 /* 旋转速率 */
        controls.update()

        let geometry = null
        let texture = null
        let material = null

        /* 判断球形还是正方体 */
        if (arrUrl.length === 1) {
          /* 圆球全景1张图片 */
          camera.position.set(0, 20, -150) /* 摄像头摆放位置 */
          texture = new THREE.TextureLoader().load(arrUrl[0])
          texture.minFilter = THREE.LinearFilter
          texture.format = THREE.RGBFormat
          material = new THREE.MeshBasicMaterial({ map: texture })
          geometry = new THREE.SphereBufferGeometry(
            canvas.height, /* 球体半径 */
            canvas.height + 100,
            canvas.height + 100
          ).toNonIndexed()
        } else {
          /* 正方体全景6张图 */
          camera.position.set(0, 0, canvas.height / 2) /* 摄像头摆放位置 */
          material = []
          for (var i = 0; i < arrUrl.length; i++) {
            var side = arrUrl[i]
            texture = new THREE.TextureLoader().load(side)
            material.push(new THREE.MeshBasicMaterial({ map: texture }))
          }
          geometry = new THREE.BoxBufferGeometry(
            canvas.height,
            canvas.height,
            canvas.height
          )
        }

        geometry.scale(-1, 1, 1)
        const mesh = new THREE.Mesh(geometry, material)

        scene.add(mesh)

        // function onWindowResize() {
        //   camera.aspect = window.innerWidth / window.innerHeight
        //   camera.updateProjectionMatrix()
        //   renderer.setSize(canvas.width, canvas.height)
        // }
        function render() {
          canvas.requestAnimationFrame(render)
          controls.update()
          renderer.render(scene, camera)
        }

        render()

        setTimeout(() => {
          wx.hideLoading()
        }, 200)
      })

  },
  onUnload: function () {
    //  释放canvas
    THREE.global.unregisterCanvas(this.data.canvasId)
  },
  touchStart(e: WechatMiniprogram.CustomEvent) {
    THREE.global.touchEventHandlerFactory("canvas", "touchstart")(e)
  },
  touchMove(e: WechatMiniprogram.CustomEvent) {
    THREE.global.touchEventHandlerFactory("canvas", "touchmove")(e)
  },
  touchEnd(e: WechatMiniprogram.CustomEvent) {
    THREE.global.touchEventHandlerFactory("canvas", "touchend")(e)
  },
})
